package com.wisemoresystem.seal.base.service;

import java.io.Serializable;
import java.util.List;

import org.ne.framework.data.model.DbModel;
import org.ne.framework.data.sql.JdbcComponent;
import org.ne.framework.data.util.ChkTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BaseService {

	@Autowired
	public JdbcTemplate jt;
	@Autowired
	public JdbcComponent jc;
	@Autowired
	public HibernateTemplate ht;

	public BaseService() {
		super();
	}

	// 查询单个对象
	public <T extends DbModel> T findObj(String hql, Object... vals) {

		List<T> list = (List<T>) ht.find(hql, vals);
		return (T) get0(list);
	}

	// 保存单个对象
	@Transactional
	public <T extends DbModel> void saveObj(T obj) {
		ht.save(obj);
	}

	@Transactional
	public <T extends DbModel> void updateObj(T obj) {
		ht.update(obj);
	}

	@Transactional
	public <T extends DbModel> void delObj(T obj) {
		obj.setStatus(-100);
		ht.update(obj);
	}

	@Transactional
	public <T extends DbModel> void delObjById(Serializable _id, Class<T> clazz) {
		T obj = ht.get(clazz, _id);
		System.err.println("obj==" + obj);
		this.delObj(obj);
	}

	@Transactional
	public <T extends DbModel> T findObjById(Serializable _id, Class<T> clazz) {
		return ht.get(clazz, _id);
	}

	public Object get0(List list) {
		if (ChkTools.isNull(list)) {
			return null;
		} else {
			return list.get(0);
		}
	}

	// Task 使用
	public long getTaskCnt(String sql, Object... objs) {
		Number cnt = (Number) jt.queryForMap(sql, objs).get("cnt");
		return cnt.longValue();
	}

}
